<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增分类
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="ID">
          <el-input v-model="searchForm.id" placeholder="分类ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.categoryName" placeholder="分类名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.categoryAlias" placeholder="分类别名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 分类列表 -->
      <el-table :data="categories" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="categoryAlias" label="分类别名" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类别名" prop="categoryAlias">
          <el-input v-model="categoryForm.categoryAlias" placeholder="请输入分类别名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

// 数据列表
const categories = ref([])
const loading = ref(false)

// 分页参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitting = ref(false)

// 表单数据
const categoryForm = reactive({
  categoryName: '',
  categoryAlias: ''
})

// 表单验证规则
const categoryRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 10, message: '分类名称长度应在1-10个字符之间', trigger: 'blur' }
  ],
  categoryAlias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { min: 1, max: 15, message: '分类别名长度应在1-15个字符之间', trigger: 'blur' }
  ]
}

// 搜索表单
const searchForm = reactive({
  id: '',
  categoryName: '',
  categoryAlias: ''
})

// 获取分类列表
const getCategories = async () => {
  loading.value = true
  try {
    const res = await request.get('/category/page', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
        id: searchForm.id || undefined,
        categoryName: searchForm.categoryName || undefined,
        categoryAlias: searchForm.categoryAlias || undefined
      }
    })
    if (res.code === 200) {
      categories.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getCategories()
}

// 页码改变
const handleCurrentChange = (val) => {
  page.value = val
  getCategories()
}

// 新增分类
const handleAdd = () => {
  dialogType.value = 'add'
  categoryForm.categoryName = ''
  categoryForm.categoryAlias = ''
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(categoryForm, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`/category/delete/${row.id}`)
      if (res.code === 200) {
        ElMessage.success('删除文章分类成功')
        getCategories()
      } else {
        ElMessage.error(res.msg || '删除文章分类失败')
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除文章分类失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let res
        if (dialogType.value === 'add') {
          const addCategoryDTO = {
            categoryName: categoryForm.categoryName,
            categoryAlias: categoryForm.categoryAlias
          }
          res = await request.put('/category/add', addCategoryDTO)
        } else {
          res = await request.put('/category', {
            ...categoryForm,
            id: categoryForm.id
          })
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
          dialogVisible.value = false
          getCategories()
        } else {
          ElMessage.error(res.msg || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
        }
      } catch (error) {
        console.error('保存分类失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getCategories()
}

// 重置
const handleReset = () => {
  searchForm.id = ''
  searchForm.categoryName = ''
  searchForm.categoryAlias = ''
  page.value = 1
  pageSize.value = 10
  getCategories()
}

onMounted(() => {
  getCategories()
})
</script>

<style scoped>
.category-container {
  min-height: 100%;
}

.category-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style> 